package com.etl.util;

import com.etl.entity.EtlBusinessDbInfo;
import com.etl.exception.GlobalException;
import lombok.extern.slf4j.Slf4j;

import java.sql.*;
import java.util.Map;

@Slf4j
public class DbUntil {

    /**
     * 执行sql 不返回结果集
     *
     * @param sql
     * @param dbInfo
     * @throws SQLException
     */
    public static String getTabelName(String sql, EtlBusinessDbInfo dbInfo) throws SQLException {


        String tabelName = "";

        PreparedStatement pstmt = null;
        Connection conn = getConn(dbInfo);
        ResultSet rs = null;
        try {
            if (conn != null) {
                pstmt = conn.prepareStatement(sql);
            }
            if (pstmt != null) {
                rs = pstmt.executeQuery();
            }
            //5）处理结果
            while(rs.next()){
                tabelName = rs.getString("tableName");
            }
        } catch (SQLException e) {
            log.error(e.getMessage());
            throw new GlobalException(2000,e.getMessage());
        } finally {
            close(conn,pstmt, null);
        }
        return tabelName;
    }



    /**
     * 执行sql 不返回结果集
     *
     * @param sql
     * @param dbInfo
     * @throws SQLException
     */
    public static void executeSql(String sql, EtlBusinessDbInfo dbInfo) throws SQLException {



        PreparedStatement pstmt = null;
        Connection conn = getConn(dbInfo);
        try {
            if (conn != null) {
                pstmt = conn.prepareStatement(sql);
            }
            if (pstmt != null) {
                pstmt.execute();
            }
        } catch (SQLException e) {
            log.error(e.getMessage());
            throw new GlobalException(2000,e.getMessage());
        } finally {
            close(conn,pstmt, null);
        }
    }


    /**
     * 获取数据库连接方法
     *
     * @param dbInfo
     * @return
     */
    public static Connection getConn(EtlBusinessDbInfo dbInfo) {
        Connection conn = null;
        try {
            Map<String, String> map = CommonUtil.pingDBUrlAndDriver(dbInfo);
            Class.forName(map.get("driver"));
            conn = DriverManager.getConnection(map.get("url"), dbInfo.getUsername(), dbInfo.getPassword());
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return conn;
    }

    /**
     * 关闭数据库连接方法
     *
     * @param pstmt
     * @param rs
     * @throws SQLException
     */
    public static void close(Connection conn,PreparedStatement pstmt, ResultSet rs) throws SQLException {
        if (conn != null) {
            conn.close();
            conn = null;
        }
        if (pstmt != null) {
            pstmt.close();
        }
        if (rs != null) {
            rs.close();
        }
    }


}
